from django.http.response import JsonResponse
from django.db.models import F, Count
from django.db.models.functions import ExtractYear, ExtractMonth
from article.models import articles as art_model
from MBlog_backend.custom_response import custom_response


# Create your views here.

def list(request):
    art_objs = art_model.objects.annotate(year=ExtractYear('create_time'), month=ExtractMonth('create_time'))
    art_objs = art_objs.values('year', 'month').annotate(articleNum=Count('id'))
    art_objs = art_objs.values('year', 'month', 'articleNum').order_by('-year','-month')
    resp = custom_response()
    archive_list = [x for x in art_objs]
    archive_list.reverse()
    resp.data_update(archive_list)
    return resp.response


def new(request):
    art_objs = art_model.objects.annotate(year=ExtractYear('create_time'), month=ExtractMonth('create_time'))
    art_objs = art_objs.values('year', 'month').annotate(articleNum=Count('id'))
    art_objs = art_objs.values('year', 'month').order_by('year','month')[:5]
    resp = custom_response()
    archive_list = [x for x in art_objs]
    archive_list.reverse()
    resp.data_update(archive_list)
    return resp.response
